package api

import (
	"gitee.com/cyanbleeze/go-image-management/internal/service"
	"gitee.com/cyanbleeze/go-image-management/pkg/app"
	"gitee.com/cyanbleeze/go-image-management/pkg/errcode"
	"github.com/gin-gonic/gin"
)

type Token struct {
}

func NewToken() Token {
	return Token{}
}

func (t Token) Post(c *gin.Context) {
	params := service.CheckAuthRequest{}
	response := app.NewResponse(c)
	valid, errs := app.BindAndValid(c, &params)
	if !valid {
		response.ToErrorResponse(errcode.InvalidParams.WithDetails(errs.Errors()...))
		return
	}

	svc := service.New(c)
	user, err := svc.CheckAuth(&params)
	if err != nil {
		response.ToErrorResponse(errcode.UnauthorizedAuthNotExist)
		return
	}
	token, err := app.GenerateToken(user.ID, user.Username)
	if err != nil {
		response.ToErrorResponse(errcode.InvalidParams)
		return
	}
	response.ToResponse(gin.H{
		"token": token,
	})
}

func (t Token) Get(c *gin.Context) {
	response := app.NewResponse(c)
	svc := service.New(c)
	user, err := svc.GetAuth()
	if err != nil {
		response.ToErrorResponse(errcode.InvalidParams)
		return
	}
	response.ToResponse(user)
}
